#!/usr/bin/python

from mqtt_client import WuxiMqttClass
from socket_server import SocketServerClass
from socket_server_mock import SocketServerMockClass
from service_control import Audio, Light
from multiprocessing import Process, Queue

def mq_run(broker, port, obj):
    mq = WuxiMqttClass(broker, port, obj)
    mq.subscribe_topic_received("wuxi/#")
    mq.run()


def tcp_run(tcp_host, tcp_port, am):
    ss = SocketServerClass(tcp_host, tcp_port)
    socket_server = ss.start()
    while True:
        client_socket, client_address = socket_server.accept()
        print(f"Connection from {client_address}")

        try:
            while True:
                content = am.get()
                data = client_socket.send(content)
                print(f"Sent: {data}")

        finally:
            client_socket.close()

def tcp_run_mock(tcp_host, tcp_port):
    ss = SocketServerMockClass(tcp_host, tcp_port)
    ss.run()
    

def main():
    mq_broker = '192.168.211.173'
    mq_port = 1883
    # mq_run(mq_broker, mq_port)


    socket_host = '192.168.211.251'
    socket_port = 8080
    am = Queue()
    audio = Audio(am)
    audio.start()

    light = Light()
    light.start(audio)
    p1 = Process(target=mq_run, args=(mq_broker, mq_port, am))
    p2 = Process(target=tcp_run, args=(socket_host, socket_port))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

def main_mock():
    mq_broker = '192.168.211.182'
    mq_port = 1883

    socket_host = '192.168.211.182'
    socket_port = 8080
    am = Queue()
    # p1 = Process(target=mq_run, args=(mq_broker, mq_port, am))
    p2 = Process(target=tcp_run_mock, args=(socket_host, socket_port))

    # p1.start()
    p2.start()
    # p1.join()
    p2.join()


if __name__ == '__main__':
    # main()
    main_mock()
